package com.yt.base.controller.order;


import com.alibaba.dubbo.common.utils.StringUtils;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.yt.base.controller.core.BaseController;
import com.yt.base.util.PinyinUtil;
import com.yt.base.vo.ProductVo;
import com.yt.core.MsgBean;
import com.yt.core.dao.filter.DynamicSQLFilterImpl;
import com.yt.core.dao.filter.QueryFilter;
import com.yt.order.api.interfaces.*;
import com.yt.order.api.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/order/product")
public class ProductController extends BaseController {
	@Autowired
	private ProductService productInfoService;
	@Autowired
	private GroupOrderService groupOrderService;
	@Autowired
	private ProductTypeService productTypeService;
	@Autowired
	private InstitutionService institutionService;

	@Autowired
	private GroupOrderProductService groupOrderProductService;

	@RequestMapping("/list")
	public ModelAndView list(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("order/product/ProductList");
		QueryFilter filter = new DynamicSQLFilterImpl();
		filter.addFilter(request.getParameterMap());
		String name = request.getParameter("name");
		//先查询机构表
		String insName = request.getParameter("insName");
		if (StringUtils.isNotEmpty(insName)) {
			mav.addObject("insName",insName);
			QueryFilter insFilter = new DynamicSQLFilterImpl();
			insFilter.addFilter("Q_pinyin_S_LK", PinyinUtil.getPinyinJianPinToUpperCase(insName.trim()));
			insFilter.setSortField("pinyin", false);
			insFilter.setPagingBean(null);
			List<Institution> list = institutionService.find(insFilter);
			StringBuffer sb = new StringBuffer();
			if (list != null && list.size() > 0) {
				for (Institution institution : list) {
					if ("".equals(sb.toString())) {
						sb.append(institution.getId());
					}else{
						sb.append(",").append(institution.getId());
					}
				}
				if(!"".equals(sb.toString())){
					filter.addFilter("Q_idInstitution_S_IN",sb.toString());
				}
			}
		}
		if (StringUtils.isNotEmpty(name)) {
			filter.addFilter("Q_name_S_LK", name);
			mav.addObject("name", name);
		}
		List<Product> list = productInfoService.find(filter);
		int count = productInfoService.count(filter);
		QueryFilter institutionFilter = new DynamicSQLFilterImpl();
		institutionFilter.setPagingBean(null);
		List<Institution> institutionList = institutionService.find(institutionFilter);
		Map<Long, String> institutionMap = Maps.newHashMap();
		for (Institution oInstitution : institutionList) {
			institutionMap.put(oInstitution.getId(), oInstitution.getName());
		}

		for (Product product : list) {
			String institutionName = institutionMap.get(product.getIdInstitution());
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(institutionName)) {
				product.setInstitutionName(institutionName);
			} else {
				product.setInstitutionName("<span style='color:red'>已删除</span>");
			}
		}
		mav.addObject("list", list);
		mav.addObject("total", count);
		mav.addObject("start", filter.getPagingBean().getStart());
		mav.addObject("limit", filter.getPagingBean().getPageSize());
		return mav;
	}

	@RequestMapping("/toAdd")
	public ModelAndView toAdd(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("order/product/ProductAdd");
		QueryFilter typeFilter=new DynamicSQLFilterImpl();
		typeFilter.setPagingBean(null);
		typeFilter.setSortField("id",false);
		List<ProductType> typeList = productTypeService.find(typeFilter);
		//机构列表
		QueryFilter filter = new DynamicSQLFilterImpl();
		filter.addFilter(request.getParameterMap());
		filter.addFilter("Q_parentId_L_EQ", "0");
		filter.setPagingBean(null);
		List<Institution> institutionList = institutionService.find(filter);
		mav.addObject("institutionList", institutionList);
		mav.addObject("productTypeList", typeList);
		return mav;
	}

	@RequestMapping("/toEdit")
	public ModelAndView toEdit(HttpServletRequest request, @RequestParam("id") Long id) {
		ModelAndView mav = new ModelAndView("order/product/ProductAdd");
		Product product = productInfoService.get(id);
		QueryFilter typeFilter=new DynamicSQLFilterImpl();
		typeFilter.setPagingBean(null);
		typeFilter.setSortField("id",false);
		List<ProductType> typeList = productTypeService.find(typeFilter);

		//机构列表
		QueryFilter filter = new DynamicSQLFilterImpl();
		filter.addFilter("Q_parentId_L_EQ", "0");
		filter.setPagingBean(null);
		List<Institution> institutionList = institutionService.find(filter);
		mav.addObject("institutionList", institutionList);
		mav.addObject("productTypeList", typeList);
		mav.addObject("bean", product);
		return mav;
	}

	@RequestMapping("/multiDel")
	@ResponseBody
	public String multiDel(@RequestParam("ids") String ids) {
		String[] idArr = ids.split(",");
		if (ids != null) {
			for (String id : idArr) {
				this.productInfoService.remove(new Long(id));
			}
		}
		return SUCCESS_JSON;
	}

	@RequestMapping("/save")
	@ResponseBody
	public Object save(Product productInfo) {
		MsgBean msg = new MsgBean();
		productInfo.setProductNo("");
//		productInfo.setIsPublic("");
//		productInfo.setAgentPrice(0l);
		if (productInfo.getId() != null) {
			this.productInfoService.update(productInfo);
		} else {
			this.productInfoService.insert(productInfo);
		}
		return msg.returnMsg();
	}

	@RequestMapping("/get")
	@ResponseBody
	public String get(@RequestParam("id") Long id) {
		Product productInfo = this.productInfoService.get(id);
		Institution institution = institutionService.get(productInfo.getIdInstitution());
		StringBuffer sb = new StringBuffer("{success:true,data:");
		JsonObject json = new JsonObject();
		json.addProperty("id", productInfo.getId());
		json.addProperty("name", productInfo.getName());
		json.addProperty("institutionId", productInfo.getIdInstitution());
		json.addProperty("institutionName", institution.getName());
		json.addProperty("price", productInfo.getPrice());
		json.addProperty("salePrice", productInfo.getSalePrice());
		json.addProperty("agentPrice", productInfo.getAgentPrice());
		json.addProperty("basePrice", productInfo.getBasePrice());
		json.addProperty("onsale", productInfo.getOnsale());
		json.addProperty("isPublic", productInfo.getIsPublic());
		json.addProperty("productNo", productInfo.getProductNo());
		json.addProperty("service", productInfo.getService());

		sb.append(json.toString());

		sb.append("}");
		return sb.toString();
	}

	@RequestMapping("/showOrHide")
	@ResponseBody
	public String showOrHide(@RequestParam("ids") String ids, @RequestParam("showOrHide") String showOrHide) {
		String[] idArr = ids.split(",");
		if (ids != null) {
			Product product;
			for (String id : idArr) {
				product = this.productInfoService.get(new Long(id));
				product.setOnsale(showOrHide);
				this.productInfoService.update(product);
			}
		}
		return "{success:true}";
	}

	@RequestMapping("/setPublic")
	@ResponseBody
	public String setPublic(@RequestParam("ids") String ids, @RequestParam("isPublic") String isPublic) {
		String[] idArr = ids.split(",");
		if (ids != null) {
			Product inst;
			for (String id : idArr) {
				inst = productInfoService.get(new Long(id));
				inst.setIsPublic(isPublic);
				productInfoService.update(inst);
			}
		}
		return "{success:true}";
	}

	@RequestMapping("/getJSON")
	@ResponseBody
	public Object getJSON(@RequestParam(value = "groupOrderId", required = false) String groupOrderId, @RequestParam("institutionId") String institutionId) {
		List<Product> list = null;
		if (StringUtils.isNotEmpty(groupOrderId) && !groupOrderId.equals("0")) {
			GroupOrder groupOrder = groupOrderService.get(Long.parseLong(groupOrderId));
			if (StringUtils.isNotEmpty(groupOrder.getProductKeyword())) {
				list = productInfoService.findProductByInstitutionIDAndKeywords(null, groupOrder.getProductKeyword());
			} else {
				list = productInfoService.findProductByGroupOrder(Long.parseLong(groupOrderId));
			}
		}
		if (list == null || list.isEmpty()) {
			list = productInfoService.findProductByInstitutionIDAndKeywords(Long.parseLong(institutionId), null);
		}
		MsgBean msg = new MsgBean();
		msg.put("data", fillProduct(list));
		//查询分院信息
		//机构列表
		QueryFilter filter = new DynamicSQLFilterImpl();
		filter.addFilter("Q_parentId_L_EQ", institutionId);
		filter.setPagingBean(null);
		List<Institution> institutionList = institutionService.find(filter);
		if (institutionList != null && institutionList.size() > 0) {
			msg.put("institutionList", institutionList);
		}
		return msg.returnMsg();
	}

	private List<ProductVo> fillProduct(List<Product> productList) {
		List<ProductVo> voList = new ArrayList<ProductVo>();
		Map<Long, Institution> map = new HashMap<Long, Institution>();
		Institution inst = null;
		ProductVo vo = null;
		for (Product product : productList) {
			vo = new ProductVo();
			vo.setId(product.getId());
			vo.setName(product.getName());
			vo.setInstitutionId(product.getIdInstitution());
			inst = map.get(product.getIdInstitution());
			if (inst == null) {
				inst = institutionService.get(product.getIdInstitution());
			}
			if (inst != null) {
				vo.setInstitutionName(inst.getName());
			}
			voList.add(vo);
		}
		return voList;
	}

	public String toBatchUpdate() {
//        HttpServletRequest request = this.getRequest();
//        String ids = this.getRequest().getParameter("ids");
//        String[] idAr = ids.split(",");
//        this.productList = new ArrayList<ProductInfo>();
//        for (int i = 0; i < idAr.length; i++) {
//            this.productList.add(productInfoService.get(Long.parseLong(idAr[i])));
//        }
		return "batchUpdate";
	}

	@RequestMapping("/batchUpdate")
	public String batchUpdate(HttpServletRequest request, HttpServletResponse response,
							  @RequestParam(value = "productSize", required = true) int productSize) {
		Product product = null;
		StringBuilder sb = new StringBuilder();
		for (int i = 1; i <= productSize; i++) {
			try {
				String id = request.getParameter("id_" + i);
				product = productInfoService.get(Long.parseLong(id));
				Long markprice = Long.parseLong(request.getParameter("price_" + i));
				Long ekangprice = Long.parseLong(request.getParameter("salePrice_" + i));
				Long agentprice = Long.parseLong(request.getParameter("agentPrice_" + i));
				Long baseprice = Long.parseLong(request.getParameter("basePrice_" + i));
				product.setAgentPrice(agentprice);
				product.setBasePrice(baseprice);
				product.setSalePrice(ekangprice);
				product.setPrice(markprice);
				productInfoService.update(product);
			} catch (Exception ex) {
				if (sb.length() > 0) {
					sb.append(",");
				}
				sb.append(i);
			}
		}

		JsonObject json = new JsonObject();
		if (sb.length() > 0) {
			json.addProperty("success", false);
			json.addProperty("rows", sb.toString());
		} else {
			json.addProperty("success", true);
		}
		return json.toString();
	}
}
